package hu.kami.twobears.techemptests;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.armedbear.lisp.Function;
import org.armedbear.lisp.JavaObject;
import org.armedbear.lisp.Packages;
import org.armedbear.lisp.Symbol;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;

public class JSONTests {

	public static void addTestHandlers (HttpServer server) {
		org.armedbear.lisp.Package twobearsPackage = Packages.findPackage("TWOBEARS");
		// Techempower json serialization test handler - called by Grizzly
		// see http://www.techempower.com/benchmarks/#section=code
		Symbol sym = twobearsPackage.findAccessibleSymbol("JSON-TEST-HANDLER");
		final Function handlerFunction = (Function) sym.getSymbolFunction();
		sym = twobearsPackage.findAccessibleSymbol("JSON-TEST-HANDLER2");
		final Function handlerFunction2 = (Function) sym.getSymbolFunction();

		server.getServerConfiguration().addHttpHandler(
				new HttpHandler() {
					public void service(Request request, Response response) throws Exception {
						addDateHeader(response);
						handlerFunction2.execute(new JavaObject(request), new JavaObject(response));
					}
				},
				"/json-abcl");
		server.getServerConfiguration().addHttpHandler(
				new HttpHandler() {
					public void service(Request request, Response response) throws Exception {
						addDateHeader(response);
						handlerFunction.execute(new JavaObject(request), new JavaObject(response));
					}
				},
				"/json-abcl2");
		server.getServerConfiguration().addHttpHandler(
				new HttpHandler() {
					public void service(Request request, Response response) throws Exception {
						addDateHeader(response);
						String str = "{\"message\":\"Hello, World!\"}";
						response.setContentLength(str.length());
						response.getWriter().write(str);
					}
				}, "/json-java");
	}
	
	private static void addDateHeader(Response response) {
		final SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
		final String date = format.format(new Date(System.currentTimeMillis()));
		response.addHeader("Date", date);
	}
}
